package com.ruc.deke.dao.impl;

import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.ArrayList;

import javax.annotation.Resource;
import javax.sql.DataSource;

import org.springframework.stereotype.Component;

import com.ruc.deke.dao.TeacherDAO;
import com.ruc.deke.model.DBRecord;
import com.ruc.deke.model.Teacher;
import com.ruc.deke.utils.ParseUtil;

@Component(value = "teacherDAOImpl")
public class TeacherDAOImpl implements TeacherDAO {

	@Resource(name = "dataSource_rucdbcourse")
	private DataSource dataSource;

	@Override
	public ArrayList<DBRecord> getTeacherByTId(String teacherId) {
		ResultSet resultSet = null;
		Statement statement = null;
		Connection connection = null;
		String sql = "select * from DB_COURSE_TEACHER where teacherid = '" + teacherId + "'";
		ArrayList<DBRecord> recordsList = new ArrayList<DBRecord>();
		try {
			connection = dataSource.getConnection();
			statement = connection.createStatement();
			resultSet = statement.executeQuery(sql);
			System.out.println("-----" + dataSource);
			recordsList = ParseUtil.toDBRecord(resultSet);
		} catch (SQLException e) {
			// e.printStackTrace();
			System.out.println("exception:" + e.getMessage());
		} finally {
			try {
				statement.close();
				connection.close();
			} catch (SQLException e) {
				// e.printStackTrace();
				System.out.println("exception:" + e.getMessage());
			}
		}
		return recordsList;
	}

	@Override
	public boolean addTeacher(Teacher teacher) {
		// TODO Auto-generated method stub
		Statement statement = null;
		Connection connection = null;
		DBRecord record = new DBRecord();
		record.setField("TEACHERID", teacher.getTeacherid());
		record.setField("TNAME", teacher.getTname());
		record.setField("PASSWD", teacher.getPasswd());
		record.setField("EMAIL", teacher.getEmail());
		record.setField("UNO", teacher.getUno());
		record.setField("MAJOR", teacher.getMajor());// 专业
		record.setField("GRADE", teacher.getGrade());
		record.setField("CLASSES", teacher.getClasses());
		record.setField("ANO", teacher.getAno());// 通过学校和数据库序号进行确定

		try {
			String sql = ParseUtil.toInsertSQL("DB_COURSE_TEACHER", record);
			connection = dataSource.getConnection();
			statement = connection.createStatement();
			statement.executeUpdate(sql);
		} catch (SQLException e1) {
			System.out.println(e1.getErrorCode() + "");
			System.out.println(e1.getMessage());
			return false;
		} catch (Exception e2) {
			System.out.println(e2.getMessage() + "");
			return false;

		}

		try {
			statement.close();
			connection.close();
		} catch (SQLException e) {
			System.out.println(e.getErrorCode());
		}
		return true;

	}

}
